package com.zwb.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zwb.boot.common.R;
import com.zwb.boot.dto.UserDto;
import com.zwb.boot.entity.Employee;
import com.zwb.boot.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author 头发又黑又长
 * @Date 2022/7/24 15:51
 * @email zwb15083976291@163.com
 */
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, username);

        Employee loginEmployee = employeeService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(loginEmployee)) {
            throw new UsernameNotFoundException("用户名密码不存在");
        }

        UserDto userDto = new UserDto(loginEmployee.getUsername(),
                passwordEncoder.encode(loginEmployee.getPassword()),
                loginEmployee.getStatus() != 0,
                true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("employee," + loginEmployee.getUsername()));
        userDto.setEmployee(loginEmployee);
        return userDto;
    }
}
